package br.com.news.business;

import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import br.com.news.business.utils.GenericBusiness;
import br.com.news.utils.business.exception.BusinessException;
import br.com.news.utils.business.interfaces.IAuditoriaBusiness;
import br.com.news.utils.business.interfaces.ICategoriaBusiness;
import br.com.news.utils.database.beans.CategoriaBean;
import br.com.news.utils.database.exception.DataBaseServiceException;
import br.com.news.utils.database.interfaces.ICategoriaServiceDb;

@Named
public class CategoriaBusiness extends GenericBusiness implements ICategoriaBusiness{

	private static final String AUDITORIA_CATEGORIA = "CATEGORIA";
	
	@Inject
	private IAuditoriaBusiness auditoriaBusiness;
	
	@Inject
	private ICategoriaServiceDb categoriaServiceDb;
	
	@Override
	public List<CategoriaBean> findAll() throws BusinessException {
		try {
			return categoriaServiceDb.findAll();
		} catch (DataBaseServiceException e) {
			throw new BusinessException(e);
		}
	}

	@Override
	public List<CategoriaBean> findCategoriaAtiva() throws BusinessException {
		try {
			return categoriaServiceDb.findCategoriaByStatus(true);
		} catch (DataBaseServiceException e) {
			throw new BusinessException(e);
		}
	}
	
	@Override
	public List<CategoriaBean> categoriasMaisAcessadas() throws BusinessException {
		try {
			List<CategoriaBean> categorias = categoriaServiceDb.categoriasMaisAcessadas();
			
			for (CategoriaBean categoria : categorias) {
				categoria.setQuantidadeAcessos(categoriaServiceDb.quantidadeCarregadas(categoria.getIdCategoria()));
			}
			
			return categorias;
		} catch (DataBaseServiceException e) {
			throw new BusinessException(e);
		}
	}
	
	@Override
	public List<CategoriaBean> findByExample(CategoriaBean categoria) {
		return categoriaServiceDb.findByExample(categoria);
	}
	
	@Override
	public List<CategoriaBean> findCategoriaByStatus(boolean status) throws BusinessException {
		try {
			return categoriaServiceDb.findCategoriaByStatus(status);
		} catch (DataBaseServiceException e) {
			throw new BusinessException(e);
		}
	}
	
	@Override
	public void update(CategoriaBean categoria) throws BusinessException {
		try {
			categoriaServiceDb.update(categoria);
			auditoriaBusiness.save(categoria.getUsuario(), categoria.getIdCategoria(), AUDITORIA_CATEGORIA);
		} catch (DataBaseServiceException e) {
			throw new BusinessException(e);
		}
	}
	
	@Override
	public void save(CategoriaBean categoria) throws BusinessException {
		try {
			long id = categoriaServiceDb.insert(categoria);
			auditoriaBusiness.save(categoria.getUsuario(), id, AUDITORIA_CATEGORIA);
		} catch (DataBaseServiceException e) {
			throw new BusinessException(e);
		}
	}

}
